package me.zhengjie.modules.security.utils;

import org.springframework.web.client.RestTemplate;
import org.springframework.stereotype.Component;

@Component
public class GeoLocationUtil {

    private static final String API_URL = "http://ip-api.com/json/";

    public String getLocationByIp(String ipAddress) {
        try {
            String url = API_URL + ipAddress;
            RestTemplate restTemplate = new RestTemplate();
            // 获取地理位置信息
            GeoLocationResponse response = restTemplate.getForObject(url, GeoLocationResponse.class);
            if (response != null && "OK".equals(response.getStatus())) {
                // 返回城市信息
                return response.getCity();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未知"; // 如果获取失败，返回"未知"
    }

    // 用于接收返回的地理位置信息
    public static class GeoLocationResponse {
        private String status;
        private String city;

        // Getters and Setters
        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }
    }
}

